/**
 * Copyright &copy; 2012-2016 <a href="https://github.com/thinkgem/jeesite">JeeSite</a> All rights reserved.
 */
package com.rambo.sdh.common.util;

import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.TemplateException;
import org.springframework.core.io.DefaultResourceLoader;
import org.springframework.core.io.Resource;

import java.io.IOException;
import java.io.StringReader;
import java.io.StringWriter;
import java.util.HashMap;
import java.util.Map;

/**
 * FreeMarkers工具类
 *
 * @author ThinkGem
 * @version 2013-01-15
 */
public class FreeMarkerUtil {

    public static String renderString(String templateString, Map<String, ?> model) throws IOException, TemplateException {
        StringWriter result = new StringWriter();
        Template t = new Template("name", new StringReader(templateString), new Configuration());
        t.process(model, result);
        return result.toString();
    }

    public static String renderTemplate(Template template, Object model) throws IOException, TemplateException {
        StringWriter result = new StringWriter();
        template.process(model, result);
        return result.toString();
    }

    public static Configuration buildConfiguration(String directory) throws IOException {
        Configuration cfg = new Configuration();
        Resource path = new DefaultResourceLoader().getResource(directory);
        cfg.setDirectoryForTemplateLoading(path.getFile());
        return cfg;
    }

    public static void main(String[] args) throws IOException, TemplateException {
        // renderString
        Map<String, String> model = new HashMap<>();
        model.put("userName", "calvin");
        String result = renderString("hello ${userName}", model);
        System.out.println(result);

        // renderTemplate
        Configuration cfg = buildConfiguration("classpath:/");
        Template template = cfg.getTemplate("testTemplate.ftl");
        String result2 = renderTemplate(template, model);
        System.out.println(result2);

        Map<String, String> model1 = new HashMap<>();
        model1.put("userName", "calvin");
        String result3 = renderString("hello ${userName} ${r'${userName}'}", model1);
        System.out.println(result3);
    }

}
